package com.legal.aid.app.config;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.legal.aid.app.domain.vo.ChatMessage;
import com.legal.aid.app.service.ChatMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * WebSocket服务
 */
@Component
@ServerEndpoint("/ws/{sid}")
public class WebSocketServer {

    // 存放会话对象
    private static Map<String, Session> sessionMap = new HashMap();

    // @Autowired // 添加@Autowired注解注入service
    // private ChatMessageService chatMessageService;

    // websocket不是spring bean管理，而是Tomcat 管理，
    // 让spring 管理非spring bean 需要静态注入，通过静态变量存储注入的服务实例,
    // 让所有 WebSocket 端点实例共享这个静态服务
    private static ChatMessageService chatMessageService;

    @Autowired
    public void setChatMessageService(ChatMessageService chatMessageService) {
        WebSocketServer.chatMessageService = chatMessageService;
    }

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid) {
        System.out.println("客户端：" + sid + "建立连接");
        sessionMap.put(sid, session);
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    /*
     * @OnMessage
     * public void onMessage(String message, @PathParam("sid") String sid) {
     * System.out.println("收到来自客户端：" + sid + "的信息:" + message);
     * 
     * }
     * 
     * @OnMessage
     * public void onMessage(String message, @PathParam("sid") String sid) {
     * System.out.println("收到来自客户端：" + sid + "的信息:" + message);
     * 
     * try {
     * // 解析收到的JSON消息
     * JSONObject jsonObject = JSON.parseObject(message);
     * String receiverId = jsonObject.getString("receiverId");
     * String content = jsonObject.getString("message");
     * 
     * // 构建转发消息
     * JSONObject response = new JSONObject();
     * response.put("senderId", sid);
     * response.put("message", content);
     * response.put("timestamp", new Date().getTime());
     * 
     * String responseMessage = response.toJSONString();
     * 
     * // 查找并发送给接收者
     * Session receiverSession = sessionMap.get(receiverId);
     * if (receiverSession != null && receiverSession.isOpen()) {
     * receiverSession.getBasicRemote().sendText(responseMessage);
     * System.out.println("消息已转发给用户：" + receiverId);
     * } else {
     * System.out.println("接收者不在线或连接已关闭：" + receiverId);
     * // 如果接收者不在线，可以选择将消息发送回发送者，告知对方不在线
     * Session senderSession = sessionMap.get(sid);
     * if (senderSession != null && senderSession.isOpen()) {
     * JSONObject offlineResponse = new JSONObject();
     * offlineResponse.put("type", "offline");
     * offlineResponse.put("message", "对方用户不在线，消息未能送达");
     * senderSession.getBasicRemote().sendText(offlineResponse.toJSONString());
     * }
     * }
     * } catch (Exception e) {
     * System.out.println("处理消息时发生错误：" + e.getMessage());
     * e.printStackTrace();
     * }
     * }
     */
    @OnMessage
    public void onMessage(String message, @PathParam("sid") String sid) {
        try {
            // 解析收到的JSON消息
            JSONObject jsonObject = JSON.parseObject(message);
            String type = jsonObject.getString("type");

            if ("read".equals(type)) {
                // 处理消息已读
                String senderId = jsonObject.getString("senderId");
                String receiverId = jsonObject.getString("receiverId");
                chatMessageService.updateMessagesToRead(Long.parseLong(senderId), Long.parseLong(receiverId));

                // 通知发送者消息已读
                Session senderSession = sessionMap.get(senderId);
                if (senderSession != null && senderSession.isOpen()) {
                    JSONObject readNotification = new JSONObject();
                    readNotification.put("type", "read");
                    readNotification.put("receiverId", sid);
                    readNotification.put("timestamp", new Date().getTime());
                    senderSession.getBasicRemote().sendText(readNotification.toJSONString());
                }
                return;
            }

            // 处理咨询结束
            if ("finishConsult".equals(type)) {
                // 处理律师发送的咨询结束
                // 发起者id lawyerId
                String senderId = jsonObject.getString("senderId");
                // 接收者id userId
                String receiverId = jsonObject.getString("receiverId");

                // 通知接收者
                Session senderSession = sessionMap.get(receiverId);
                if (senderSession != null && senderSession.isOpen()) {
                    JSONObject finishConsultNotification = new JSONObject();
                    finishConsultNotification.put("senderId", senderId);
                    finishConsultNotification.put("type", "finishConsult");
                    finishConsultNotification.put("receiverId", receiverId);
                    finishConsultNotification.put("timestamp", new Date().getTime());
                    senderSession.getBasicRemote().sendText(finishConsultNotification.toJSONString());
                }
                return;
            }

            String receiverId = jsonObject.getString("receiverId");
            String content = jsonObject.getString("content");
            String senderName = jsonObject.getString("senderName");
            String senderAvatar = jsonObject.getString("senderAvatar");

            // 构建转发消息
            JSONObject response = new JSONObject();
            response.put("senderId", sid);
            response.put("message", content);
            response.put("senderName", senderName);
            response.put("senderAvatar", senderAvatar);
            response.put("timestamp", new Date().getTime());
            response.put("type", "message");

            String responseMessage = response.toJSONString();

            // 查找并发送给接收者
            Session receiverSession = sessionMap.get(receiverId);
            if (receiverSession != null && receiverSession.isOpen()) {
                receiverSession.getBasicRemote().sendText(responseMessage);
                System.out.println("消息已转发给用户：" + receiverId);

                ChatMessage chatMessage = new ChatMessage();
                chatMessage.setSenderId(sid);
                chatMessage.setReceiverId(receiverId);
                chatMessage.setContent(content);
                chatMessage.setSendTime(new Date());
                chatMessage.setStatus("1"); // 0表示已读
                chatMessage.setCreateTime(new Date());
                // if (chatMessageService == null) {
                // System.err.println("chatMessageService is null!");
                // return;
                // }
                try {
                    System.out.println(chatMessage);
                    chatMessageService.saveMessage(chatMessage);
                    System.out.println("消息保存成功");
                } catch (Exception e) {
                    System.out.println("保存消息失败：" + e.getMessage());
                    e.printStackTrace();
                }

                // 发送通知消息
                JSONObject notification = new JSONObject();
                notification.put("type", "notification");
                notification.put("title", "新消息");
                notification.put("content", senderName + "给您发送了一条新消息");
                notification.put("senderId", sid);
                notification.put("senderName", senderName);
                notification.put("timestamp", new Date().getTime());

                receiverSession.getBasicRemote().sendText(notification.toJSONString());
            } else {
                ChatMessage chatMessage = new ChatMessage();
                chatMessage.setSenderId(sid);
                chatMessage.setReceiverId(receiverId);
                chatMessage.setContent(content);
                chatMessage.setSendTime(new Date());
                chatMessage.setStatus("0"); // 0表示未读
                chatMessage.setCreateTime(new Date());

                try {
                    System.out.println(chatMessage);
                    chatMessageService.saveMessage(chatMessage);
                    System.out.println("离线消息保存成功");
                } catch (Exception e) {
                    System.out.println("保存离线消息失败：" + e.getMessage());
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            System.out.println("处理消息时发生错误：" + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 连接关闭调用的方法
     *
     * @param sid
     */
    @OnClose
    public void onClose(@PathParam("sid") String sid) {
        System.out.println("连接断开:" + sid);
        sessionMap.remove(sid);
    }

    // /**
    // * 群发
    // *
    // * @param message
    // */
    // public void sendToAllClient(String message) {
    // Collection<Session> sessions = sessionMap.values();
    // for (Session session : sessions) {
    // try {
    // // 服务器向客户端发送消息
    // session.getBasicRemote().sendText(message);
    // } catch (Exception e) {
    // e.printStackTrace();
    // }
    // }
    // }

    /**
     * 发送消息给指定客户端
     *
     * @param sid     客户端ID
     * @param message 消息内容
     */
    public void sendToClient(String sid, String message) {
        Session session = sessionMap.get(sid);
        if (session != null && session.isOpen()) {
            try {
                System.out.println(session);
                System.out.println(message);
                session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                System.out.println("发送消息失败：" + e.getMessage());
                e.printStackTrace();
            }
        }
    }

}
